//
//  ReimbursementDetailViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/11/19.
//  Copyright © 2018 xyxorigation. All rights reserved.
//

import UIKit

class ReimbursementDetailViewController: PagedViewController {

    var id: String = ""
    
    let approvalBtn = UIButton.init(type: .system)
    
    var ifneedapproal = false
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.view.backgroundColor = .black
        
        if ifneedapproal {
            
            approvalBtn.setTitle("审批意见", for: .normal)
            
            approvalBtn.setTitleColor(UIColor.white, for: .normal)
            
            approvalBtn.backgroundColor = UIColor.mainColor
            
            approvalBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
            
            approvalBtn.addTarget(self, action: #selector(approvalAction(btn:)), for: .touchUpInside)
            
            self.view.addSubview(approvalBtn)
            
        }
        self.view.backgroundColor = .black
        for view in self.view.subviews {
            if view is UIScrollView {
                let scroll = view as! UIScrollView
                scroll.bounces = false
            }
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(dtl), name: NSNotification.Name("RefreshDetail"), object: nil)
        self.load(with: "detail")
        // Do any additional setup after loading the view.
    }
    
    @objc func dtl()->Void{
        self.pop()
    }
    
    @objc func approvalAction(btn: UIButton)->Void{
        let approval = ApprovalSuggestionViewController()
        
        approval.applyId = self.id
        
        approval.netPath = ReimbursementApproval
        
        approval.businessType = "50"
        
         self.navigationController?.present(vc: approval)
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        if ifneedapproal {
            approvalBtn.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.height - 55), size: CGSize(width: self.view.width, height: 55))
            
            page.view.frame = CGRect(origin: CGPoint(x: 0, y:self.trayView.bottom), size: CGSize(width: self.view.width, height: self.view.height - self.trayView.height - approvalBtn.height))
        }
    }
    
    override func configTitles() -> Array<String> {
        return ["基本信息","审批记录"]
    }
    
    override func configViewControllers() -> [UIViewController] {
        let rei = ReimbursementTableViewController()
        rei.filePath = .Finacial
        return [rei,ApprovalRecordListViewController()]
    }

    override func success(for name: String) -> NetSuccess {
        
        func suc(json: JSON)->Void{
            if let success = json.contents?["success"]?.bool {
                if success == true {
                    if let data = json.contents?["data"]?.contents {
                        let operation = data["operation"]?.bool
                        if operation == true {
                            self.approvalBtn.isEnabled = true
                        } else {
                            self.approvalBtn.isEnabled = false
                        }
                        var contents: Array<Dictionary<String,String?>> = []
                        if let details = data["details"]?.contents {
                            contents.append(["项目名称:":details["projectName"]?.rawString() ?? ""])
                            contents.append(["报销人:": details["concernedHuman"]?.string ?? ""])
                            contents.append(["同行人员:":details["peerStaffName"]?.rawString() ?? ""])
                            contents.append(["出差人数:":details["travelNumber"]?.rawString() ?? ""])
                            contents.append(["出差天数:": details["daysOfTravel"]?.string])
                            contents.append(["出差事由:":details["businessTrip"]?.rawString() ?? ""])
                            let travelAllowance = (details["travelAllowance"]?.double ?? 0) / 100.0
                            contents.append(["交通补助:":String(format: "%.2f", travelAllowance)])
                            let foodAllowance = (details["foodAllowance"]?.double ?? 0) / 100.0
                            contents.append(["伙食补助(元):":String(format: "%.2f", foodAllowance)])
                            let totalCost = (details["totalCost"]?.double ?? 0) / 100.0
                            contents.append(["费用合计(元):":String(format: "%.2f", totalCost)])
                            if totalCost == 0 {
                                contents.append(["费用合计大写:":"-"])
                            } else {
                                contents.append(["费用合计大写:":totalCost.rmbOldStyle])
                            }
                            contents.append(["备注:":details["reamake"]?.rawString() ?? ""])
                            let controller = self.ctls[0] as! ReimbursementTableViewController
                            controller.source = contents;
                            if let attachfiles = details["attachFiles"]?.array {
                                controller.documents = attachfiles
                            }
                            var dts: [[Dictionary<String,String?>]] = []
                            if let list = details["reimbursementDetails"]?.array {
                                for item in list {
                                    var element: [Dictionary<String,String?>] = []
                                    element.append(["出发日期:":item["departureTime"].rawString() ?? ""])
                                    element.append(["到达日期:":item["arriveTime"].rawString() ?? ""])
                                    element.append(["出发地点:":item["departurePlace"].rawString() ?? ""])
                                    element.append(["到达地点:":item["arrivalPlace"].rawString() ?? ""])
                                    let transportModesName = item["transportModesName"].rawString() ?? ""
                                    if transportModesName == "null" {
                                        element.append(["交通方式:":""])
                                    } else {
                                        element.append(["交通方式:":transportModesName])
                                    }
//                                    element.append(["交通方式":item["transportModesName"].rawString() != nil ?? ""])
                                    let transportfee = (item["transportationCost"].double ?? 0) / 100.0
                                    element.append(["交通费(元):": String(format: "%.2f", transportfee)])
                                    let hotelfee = (item["hotelExpense"].double ?? 0) / 100.0
                                    element.append(["住宿费(元):":String(format: "%.2f", hotelfee)])
                                    let ifOverStand = item["whetherOverStand"].bool ?? false
                                    if ifOverStand  {
                                        element.append(["是否超标:":"是"])
                                    } else {
                                        element.append(["是否超标:":"否"])
                                    }
                                    dts.append(element)
                                }
                            }
                            controller.details = dts
                            controller.tableView.reloadData()
                        
                            if let approvalList = data["approvalList"]?.array {
                                let approval = self.ctls[1] as! ApprovalRecordListViewController
                                approval.source = approvalList.map({ (j) -> JSON in
                                    var json: [String: Any] = [:]
                                    json["approvalResult"] = j.contents?["approvalResult"]?.int ?? 0
                                    json["createTime"] = j.contents?["applyTime"]?.rawString() ?? ""
                                    json["approvalOpinion"] = j.contents?["approvalOpinion"]?.rawString() ?? ""
                                    json["createUserVal"] = j.contents?["approverName"]?.rawString() ?? ""
                                    return JSON(json)
                                })
                                approval.tableView.reloadData()
                            }
                        }
                    }
                } else {
                    self.alert(json.contents?["errorMsg"]?.rawString())
                }
            }
        }
        
        return suc
    }
    
    override func method(for name: String) -> NetMethod {
        return .get
    }
    
    override var names: Array<String>{
        get{
            return  ["detail","approval"]
        }
    }
    
    override func path(for name: String) -> String {
        if name == "detail" {
            return ReimbursementDetail
        } else {
            return ""
        }
    }
    
    override func param(for name: String) -> Dictionary<String, Any> {
        return ["id":id,"businessType":50]
    }
    
    
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
